  <template>
  <el-upload
    v-bind="$attrs"
    class="w100 common-upload"
    :action="action"
    :headers="headers"
    :on-remove="onUploadRemove"
    :on-success="onUploadSuccess"
    :on-error="onError"
    :on-preview="onPreview"
    :file-list="fileList"
  >
    <slot name="default">
      <el-button type="primary">
        <el-icon>
          <ele-Upload />
        </el-icon>
        点击上传
      </el-button>
    </slot>
    <template #tip>
      <slot name="tip"></slot>
    </template>
  </el-upload>
  <ElImageViewer
    v-if="viewerVisible"
    teleported
    :url-list="urlList"
    @close="viewerVisible = false"
  />
</template>

<script lang="ts" setup name="commonUpload">
import { ref } from 'vue';
import { ElImageViewer, ElMessage } from 'element-plus';
import { useUpload } from '/@/hooks/use-upload';
import { pick } from 'lodash/fp';
import { getPreviewUrl } from '/@/utils';

const { action, headers } = useUpload();

const emit = defineEmits(['change']);

const pickFile = pick(['name', 'origin_name', 'size', 'url', 'download_url']);

const fileList = ref<any[]>([]);
const urlList = ref<string[]>([]);
const viewerVisible = ref<boolean>(false);

const normalizeFileList = () => {
  return fileList.value.map((item) => {
    if (item.response) {
      return pickFile(item.response.data);
    }
    return item;
  });
};

const onUploadSuccess = (response: any, file: any, files: any[]) => {
  if (response.code !== 200) {
    ElMessage.error('上传失败');
    return;
  }

  fileList.value = files;
  emit('change', fileList.value, response);
};

const onError = () => {
  ElMessage.error('上传失败');
};

const onUploadRemove = (file: any, files: any[]) => {
  fileList.value = files;
  emit('change', fileList.value);
};

const setFileList = (files: any[]) => {
  fileList.value = files;
};

const onPreview = (item: any) => {
  urlList.value = [getPreviewUrl(item?.response?.data?.name || item.name)];
  viewerVisible.value = true;
};

defineExpose({
  normalizeFileList,
  setFileList,
  fileList
});
</script>

<style lang="scss">
.my-upload {
  .el-upload--picture-card {
    width: 100px;
    height: 100px;
  }

  .el-upload-list--picture-card .el-progress {
    width: 90px;
  }

  .el-upload-list--picture-card .el-progress .el-progress-circle {
    width: 90px !important;
    height: 90px !important;
  }

  .el-upload-list--picture-card .el-upload-list__item {
    width: 100px;
    height: 100px;
    font-size: 30px;
  }
}
</style>
